<?php

App::uses('CustomDataModel', 'Base.Model');
App::uses('ConfigurationKeys', 'ConfigurationKeys.Lib');

class Tag extends CustomDataModel {

    public $displayField = 'name';
    public $validate = array(
        'name' => array(
            'notempty' => array(
                'rule' => array('notempty'),
            ),
            'isUnique' => array(
                'rule' => array('isUnique'),
            ),
        ),
    );
    public $hasMany = array(
        'RawFileTag',
        'SourceDocumentTag',
    );

    protected function customData() {
        $sharedFilesDirectory = ConfigurationKeys::getRequiredKeyValue('shared_files_directory');
        if (!is_readable($sharedFilesDirectory) || !is_dir($sharedFilesDirectory)) {
            return array();
        }
        $sharedFilesDirectoryIterator = new DirectoryIterator($sharedFilesDirectory);

        $data = array();

        while ($sharedFilesDirectoryIterator->valid()) {
            if (!$sharedFilesDirectoryIterator->isDot() && $sharedFilesDirectoryIterator->isDir()) {
                $data[] = array(
                    'name' => $sharedFilesDirectoryIterator->getFilename(),                    
                );
            }
            $sharedFilesDirectoryIterator->next();
        }

        return $data;
    }

    public function absolutePath($tag) {
        return ConfigurationKeys::
                        getRequiredKeyValue('shared_files_directory') .
                '/' . $tag[$this->alias]['name'];
    }

    protected function customSave($oldData, $newData) {
        if (empty($oldData)) {            
            return mkdir($this->absolutePath(array($this->alias => $newData)));
        } else {
            $tag = $this->findById($newData['id']);
            return rename(
                            $this->absolutePath(array($this->alias => $oldData))
                            , $this->absolutePath(array($this->alias => $newData))
            );
        }
    }

    protected function customDelete($row) {
        foreach($this->RawFileTag->findAllByTagId($row['id']) as $rawFileTag) {
            Basics::deleteModelOrThrowException($this->RawFileTag, $rawFileTag);
        }
        return rmdir($this->absolutePath(array($this->alias => $row)));
    }

}

?>
